from . import pfs
from flask import render_template, redirect, request, url_for, flash
from flask_login import login_required, current_user
from ..models import Student, Course, Takes, Inputbox, Prerequisite, Bill, Professor, Section, Openingconfig
import datetime
from .. import db
from ..models import Teaches
from .forms import GradeForm


@pfs.route('/professor-home', methods=['GET', 'POST'])
@login_required
def professor_home():
    # 教师的主页
    # 本页面提供链接到
    # 1. pfs.professor_choose_course
    # 2. pfs.professor_input_box
    # 3. pfs.professor_choose_course_to_give_grades
    today = datetime.datetime.today()
    name = current_user.get_name()
    greeting = name + "老师，您好！现在是" + str(today.year) + "年" + str(today.month) + "月" + str(today.day) + "日，" + str(
        today.hour) + "时" + str(
        today.minute) + "分"

    new_messages = Inputbox.query.filter(Inputbox.user_id == current_user.get_id()).filter(
        Inputbox.hasBeenRead == False).order_by(Inputbox.timestamp.desc()).all()  # 未读消息(hasBeenRead为False)
    if len(new_messages) > 0:
        flash('您有新的消息，请查看！')
    return render_template('professor/professor_home.html', greeting=greeting)


@pfs.route('/professor-choose-course', methods=['GET', 'POST'])
@login_required
def professor_choose_course():
    # 本路由负责列出可选的课程和已选的课程
    # 可选的课程满足
    # 1. 本学期的课
    # 2. 暂时没有老师选择教的课
    today = datetime.datetime.today()
    thisSemester = str(today.year)
    if int(today.month) < 7:
        thisSemester += "1"
    else:
        thisSemester += "2"
    section_all = Section.query.filter(Section.semester == thisSemester).all()  # 存放可选课程
    teaches = Teaches.query.all()
    section_has_professor = [t.section for t in teaches]
    section_list = []
    for s in section_all:
        if s not in section_has_professor:
            section_list.append(s)

    openingobj = Openingconfig.query.first()
    opening = openingobj.value
    teaches = Teaches.query.filter(Teaches.professor_id == current_user.get_id()).all()
    taken_section_list = [t.section for t in teaches]  # 存放已选的课程
    return render_template('professor/professor_choose_course.html',
                           open=opening,
                           section_list=section_list, taken_section_list=taken_section_list)


# ----------------------------------
# 2020/06/11更新
# 加入查看课程简介功能
@pfs.route('/professor-view-course-information/<int:section_id>', methods=['GET', 'POST'])
def professor_view_course_information(section_id):
    section = Section.query.filter(Section.section_id == section_id).first()
    course = section.course
    return render_template('professor/professor_view_course_information.html', course=course)


# ----------------------------------


@pfs.route('/professor-take-course/<int:section_id>', methods=['GET', 'POST'])
@login_required
def professor_take_course(section_id):
    # 本路由根据给定的course_id，查询本课程是否已被别老师教了
    # 如果是，则
    teaches = Teaches.query.filter(Teaches.section_id == section_id).first()
    course_id = Section.query.filter(Section.section_id == section_id).first().course_id
    if teaches:
        flash('选课失败，该课程已被其他老师所选！')
        return redirect(url_for('pfs.professor_choose_course'))
    else:
        # 如果没有，则可以教这门课
        teaches = Teaches(professor_id=current_user.get_id(), section_id=section_id,
                          course_id=course_id)
        db.session.add(teaches)
        db.session.commit()
    return redirect(url_for('pfs.professor_choose_course'))


@pfs.route('/professor-cancel-course/<int:section_id>', methods=['GET', 'POST'])
@login_required
def professor_cancel_course(section_id):
    teaches = Teaches.query.filter(Teaches.professor_id == current_user.get_id()).filter(
        Teaches.section_id == section_id).first()
    print(teaches)
    db.session.delete(teaches)
    db.session.commit()

    takes = Takes.query.filter(Takes.section_id == section_id).all()
    for t in takes:
        message = "你所选的<<" + t.course.course_name + ">>已经被授课教师取消,请及时完善课表"
        timestamp = datetime.datetime.now()
        inputbox = Inputbox(user_id=t.student_id, message=message, timestamp=timestamp, hasBeenRead=False)
        db.session.add(inputbox)
        db.session.delete(t)
    db.session.commit()

    return redirect(url_for('pfs.professor_choose_course'))


@pfs.route('/professor-choose-course-to-give-grades', methods=['GET', 'POST'])
@login_required
def professor_choose_course_to_give_grades():
    # 本路由列出本教授在教的课程
    # 存放在course_list里
    # 本路由有点类似于pfs.choose_course，但不同的是，这个界面仅列出已教的课程
    # 并且本路由前端每个课程提供一个"查看"链接，转到下一个路由，即pfs.professor_list_all_students_who_take_this_course
    section_list = Teaches.query.filter(Teaches.professor_id == current_user.get_id()).all()
    return render_template('professor/professor_choose_course_to_give_grades.html',
                           section_list=section_list)


@pfs.route('/professor-list-all-students-who-take-this-course/<int:section_id>', methods=['GET', 'POST'])
@login_required
def professor_list_all_students_who_take_this_course(section_id):
    # 本路由根据course_id参数
    # 查询选了这个course(primary)的学生，并根据学生id，返回这些学生
    takes = Takes.query.filter(Takes.section_id == section_id).all()  # student_list
    student_list = [[t.student, t.grade] for t in takes]

    section = Section.query.filter(Section.section_id == section_id).first()
    # 前端列举出选了这门课的学生，每个学生提供一个链接，转到下一个路由，即pfs.professor_submit_grades(该路由接受学生id，以及本课程的id)
    return render_template('professor/professor_list_all_students_who_take_the_course.html',
                           student_list=student_list,
                           section=section)


@pfs.route('/professor-submit-grades/<int:student_id>_<int:section_id>', methods=['GET', 'POST'])
@login_required
def professor_submit_grades(student_id, section_id):
    # 本路由用于教师提交某门课某学生的成绩
    # 这需要教师填写表单：
    form = GradeForm()
    if form.validate_on_submit():

        if not check_grade_format(form.grade.data):
            flash('成绩应为空值或为"A","B","C","D","F"和"I"六个等级中的一个！请输入正确的成绩！')
            return render_template('professor/professor_submit_grades.html', form=form)

        if form.grade.data == '':
            flash('已删除该学生成绩!')
        take = Takes.query.filter(Takes.student_id == student_id, Takes.section_id == section_id).first()

        if take is None:
            flash('删除失败！数据库异常！')

        take.grade = form.grade.data
        db.session.add(take)
        db.session.commit()
        flash('录入成绩成功！')
        return redirect(url_for('pfs.professor_list_all_students_who_take_this_course',
                                section_id=section_id))
    return render_template('professor/professor_submit_grades.html', form=form)


# ------------------------------
# 2020年6月11日 22:04:43 更新
# 检查老师给学生的成绩表单数据是否合理
def check_grade_format(grade):
    """
    检查成绩是否合理，即为A,B,C,D,F,I中的一个
    :param grade: 表单输入的成绩，为字符串类型
    :return: 若合理则返回True，否则返回False
    """
    return len(grade) in (0, 1) and grade in ("A", "B", "C", "D", "F", "I", "")

    # ------------------------------


@pfs.route('/professor-input-box', methods=['GET', 'POST'])
@login_required
def professor_input_box():
    # 本路由为教师查看消息，类似于学生的消息列表
    # 查询input_box中id=current_user.get_id()的消息，按时间排序(不是必要，因为new_message可根据颜色标出，但排序更好)，并分成已读消息和未读消息
    # 已读消息 old_messages，未读消息 new_messages，如果new_messages为空，则置hasUnreadMessages=True
    old_messages = Inputbox.query.filter(Inputbox.user_id == current_user.get_id()).filter(
        Inputbox.hasBeenRead).order_by(Inputbox.timestamp.desc()).all()  # 已读消息(hasBeenRead为True)
    new_messages = Inputbox.query.filter(Inputbox.user_id == current_user.get_id()).filter(
        Inputbox.hasBeenRead == False).order_by(Inputbox.timestamp.desc()).all()  # 未读消息(hasBeenRead为False)
    return render_template('professor/professor_input_box.html',
                           old_messages=old_messages,
                           new_messages=new_messages)


# input_box的辅助路由，仅处理数据，无实际界面，数据处理完成后回到input_box界面
@pfs.route('/professor-mark-all_messages_as_read', methods=['GET', 'POST'])
@login_required
def professor_mark_all_messages_as_read():
    # 本路由将所有消息标记为已读
    # 修改数据库，input_box里的所有id=current_user.student_id的消息的hasBeenRead项目置为True
    # 注意处理查询结果为None的情况
    # 处理完成后返回到消息界面
    inputbox = Inputbox.query.filter(Inputbox.user_id == current_user.get_id()).filter(
        Inputbox.hasBeenRead == False).all()
    for item in inputbox:
        item.hasBeenRead = True

    db.session.commit()
    return redirect(url_for('pfs.professor_input_box'))
